﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GLCommon;

namespace Chemistry.ViewModels
{
    using System.IO;
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;

    using Chemistry.Models;
    using Chemistry.Tools;

    using GalaSoft.MvvmLight.Command;

    using MahApps.Metro.Controls.Dialogs;
    

    public class K3InputNumberViewModel:VmBase
    {
        private bool _isButtonEnabled = true;
        private IDialogCoordinator _dialogCoordinator;
        ProgressDialogController controller = null;


        private string _number;
        /// <summary>
        /// 准考证号
        /// </summary>
        public string Number
        {
            get { return _number; }
            set { _number = value; RaisePropertyChanged("Number"); }
        }

        private Examinee _examinee;
        public Examinee Examinee
        {
            get { return _examinee; }
            set { _examinee = value; RaisePropertyChanged("Examinee"); }
        }

        private ImageSource _bursh;

        public ImageSource ImageSource
        {
            get { return _bursh; }
            set { _bursh = value; RaisePropertyChanged("ImageSource"); }
        }

        public RelayCommand BeginExamCommand { get; set; }

        public K3InputNumberViewModel()
        {
            CommitCommand = new RelayCommand(CommitExec,
                () => !string.IsNullOrEmpty(Number) && _isButtonEnabled);

            BeginExamCommand = new RelayCommand(BeginExam);

            Register<string>(this, MessageToken.k3InputNumberOver, async (i) =>
            {
                this.Number = i;
                CommitExec();
            });

            Register<object>(this, MessageToken.K3ExamingOver, async (i) =>
            {
                this.Number =String.Empty;
                Examinee = null;
                ImageSource = null;
            });

            Register<DialogCoordinator>(this, MessageToken.K3InputLoad,
                (i) =>
                {
                    this._dialogCoordinator = i;
                });
        }

        private async void BeginExam()
        {
            controller = await _dialogCoordinator.ShowProgressAsync(this, "获取题目中...", "");
            controller.SetIndeterminate();
            string url = string.Format("Question/GetQuestion?worktype={0}", this.Examinee.ExamType);
            var questions = await HttpBaseQuestion.GetAsync<List<QuestionInfo>>(url);
            if (questions == null || questions.Count<3)
            {
                await controller.CloseAsync();
                MessageBox.Show("未找到合适的题目", "提示", MessageBoxButton.OK);
                return;
            }
            var ids = new List<int>();
            questions.ForEach(i => ids.Add(i.Id));
            var options = await HttpBaseQuestion.PostAsJsonAsync<List<OptionsInfo>>("Question/GetOptions", ids);
            await controller.CloseAsync();

            K3ExamMessage message = new K3ExamMessage()
                                        {
                                            QuestionInfoes = questions,
                                            Examinee = Examinee,
                                            OptionsInfoes = options
                                        };
           
            Send<K3ExamMessage>(message, MessageToken.K3BeginExaming);
        }

        private async void CommitExec()
        {
            _isButtonEnabled = false;
            await Execute();
            _isButtonEnabled = true;
        }

        private async Task Execute()
        {
            Examinee = await GetExaminee();
            if (Examinee != null)
            {
                Examinee.TicketId = Number;
                Send<Examinee>(Examinee, MessageToken.K3ShowConfirm);

            }
        }

        private async Task<Examinee> GetExaminee()
        {
            controller = await _dialogCoordinator.ShowProgressAsync(this, "获取考生信息...", "");
            controller.SetIndeterminate();
            Examinee examinee = null;
            string getexamineeUrl = string.Format("GetExaminee?nr={0}&session={1}", arg0: Number, arg1: HttpTool.Session);
            var result = await HttpTool.GetAsync<ExamineeInfoApi>(getexamineeUrl);
            await controller.CloseAsync();

            if (result.status == 0 && result.examinee != null)
            {
                if (!result.subject.Contains("xc"))
                {
                    MessageBox.Show("该考生已完成考试，不能重复考试", "提示", MessageBoxButton.OK);
                }
                else
                {
                    examinee = new Examinee
                                   {
                                       Name = result.examinee.name,
                                       ExamType = result.examinee.WTAdded,
                                       TicketId = Number
                                   };

                    string info = string.Format("考生{0}登录", examinee.Name);
                    LogTool.WriteInfoLog(info);
 
                    if (!string.IsNullOrEmpty(result.examinee.photo))
                        examinee.Pictrue = Convert.FromBase64String(result.examinee.photo);
                    else
                    {
                        using (FileStream fs = new FileStream(@"../../Images/nophoto.jpg", FileMode.Open))
                        {
                            int len = (int)fs.Length;
                            byte[] b = new byte[len];
                            fs.Read(b, 0, len);
                            examinee.Pictrue = b;
                        }
                    }

                    ImageBrush brush = new ImageBrush();
                    ImageSourceConverter converter = new ImageSourceConverter();
                    this.ImageSource = (ImageSource)converter.ConvertFrom(examinee.Pictrue);
                }
            }
            else
            {
                MessageBox.Show("未找到考生信息", "提示", MessageBoxButton.OK);
            }
            return examinee;
        }
    }
}
